<template>
  <view class="root">
    <map id="myMap" style="width: 100%; height: 876rpx;position: relative;" :latitude="latitude" :longitude="longitude"
      :scale="mapscale" :markers="markers" :enable-3D="true" :show-location="true" :polyline="polyline"
      :polygons="polygons" @markertap="handleMarkerClick">

      <cover-view slot="callout">
        <block v-for="item in customCalloutMarkerIds" :key="item.id">
          <cover-view class="customCallout" :marker-id="item.id">
            <cover-view class="time-text">
              {{item.createTime}}
            </cover-view>
            <cover-view class="content-address">
              {{item.address}}
            </cover-view>
          </cover-view>
        </block>
      </cover-view>
    </map>
    <view class="top-item" v-if="details.length">
      <view class="name">
        最新一次位置信息
      </view>
      <view class="address">
        {{details[0].address}}
      </view>
    </view>

    <view class="bottom">
      <view class="t-box">
        <view class="time-item" :class="days == 1 ? 'time-selected':''" @click="changeDay(1)">最近1天</view>
        <view class="time-item" :class="days == 3 ? 'time-selected':''" @click="changeDay(3)">最近3天</view>
      </view>
      <uni-datetime-picker v-model="datetimerange" type="daterange" :start="startDate" :end="timeEnd" rangeSeparator="至"
        ref="datetimePickerRef" />

      <view class="btn-box">
        <u-button type="primary" text="查询并播放轨迹" :custom-style="btnStyle" @click="handleSearch"></u-button>
      </view>

      <view class="btn-style">
        <view class="c-item" v-for="item in details" :key="item" @click="handleAddressInfo(item)">
          <view class="solid-style">
          </view>
          <view class="b-item">
          </view>
          <view class="style-b">
            <view class="b-time">{{item.createTime}}</view>
            <view class="b-address">{{item.address}}</view>
          </view>
        </view>
      </view>
    </view>
    <yy-watermark></yy-watermark>
  </view>
</template>

<script>
  import {
    deviceinfoTrajectory
  } from '../api/api';
  import moment from '../utils/moment';
  import {
    Toast,
    daysBetween,
    getEndOfDayTimeAlternative,
    getOptionsParams,
    getZeroTimeOfDayAlternative,
    isLoading
  } from '../utils/util';

  export default {
    data() {
      return {
        latitude: '',
        longitude: '',
        mapscale: 14,
        markers: [],
        btnStyle: {
          background: 'linear-gradient( 90deg, #51B1FF 0%, #1790F2 100%)',
          'border-radius': '48rpx 48rpx 48rpx 48rpx',
          height: '96rpx',
          width: '680rpx',
          margin: '0 auto'
        },
        datetimerange: [],
        polyline: [],
        polygons: [],
        selected: true,
        days: 1,
        routerParams: {},
        details: [],
        timer: null,
        requestId: null,
        timeEnd: moment().valueOf(),
        startDate: moment().subtract(1, 'year'),
        customCalloutMarkerIds: []
      }
    },
    onLoad(options) {
      this.routerParams = getOptionsParams(options)

      let time = new Date()
      const start = getZeroTimeOfDayAlternative(time)
      const end = getEndOfDayTimeAlternative(time)
      // 设置一下时间
      this.datetimerange = [moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD')]
      this.getDetail(start, end)
    },
    methods: {
      changeDay(days) {
        this.days = days
        if (days == 1) {
          let time = new Date()
          const start = getZeroTimeOfDayAlternative(time)
          const end = getEndOfDayTimeAlternative(time)
          this.datetimerange = [moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD')]
          this.getDetail(start, end)
        } else {
          let time = moment().subtract(2, 'days')
          const start = getZeroTimeOfDayAlternative(time)


          let timeEnd = new Date()
          const end = getEndOfDayTimeAlternative(timeEnd)
          this.datetimerange = [moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD')]
          this.getDetail(start, end)
        }
      },
      getDetail(startTime, endTime) {
        const params = {
          imei: this.routerParams.imei,
          startTime,
          endTime
        }
        isLoading(true)
        deviceinfoTrajectory(params)
          .then((res) => {
            this.details = res.result
            if (res.result.length) {
              let points = this.details.map((item) => {
                return {
                  id: item.id,
                  latitude: item.lat,
                  longitude: item.lon,
                  createTime: item.createTime,
                  address: item.address
                }
              })
              this.translateMarkerFun(points)
            } else {
              this.markers = []
              if (this.timer) {
                clearInterval(this.timer)
              }
              this.polyline = []
              Toast('暂无轨迹！')
            }
          })
          .finally(() => {
            isLoading(false)
          })
      },

      translateMarkerFun(path) {
        let polyline = [{
          points: [],
          color: "#FC6F2EDD",
          width: 2,
          dottedLine: false
        }]
        // 先清除 marker  和线
        this.markers = []
        this.customCalloutMarkerIds = []
        this.polyline = [...polyline]
        if (this.timer) {
          clearInterval(this.timer)
        }
        path.reverse()
        let mpCtx = uni.createMapContext('myMap')

        this.mapContext = uni.createMapContext('myMap', this);
        this.mapContext.includePoints({
          points: path,
          padding: [100, 50, 50, 50]
        });

        let i = 0

        const renderPoint = () => {

          if (i > path.length - 1) {
            clearInterval(this.timer)
            return
          }
          this.customCalloutMarkerIds.push({
            id: Number(path[i].id),
            address: path[i].address,
            createTime: path[i].createTime
          })
          this.markers.push({
            id: Number(path[i].id),
            latitude: path[i].latitude,
            longitude: path[i].longitude,
            iconPath: '/static/icons/area-icon.png',
            content: 'hihihi',
            width: 20,
            height: 20,
            customCallout: {
              anchorY: 0,
              anchorX: 0,
              display: 'BYCLICK'
            },
          })
          if (path.length > 2) {
            polyline[0].points = path.slice(0, i + 2)
            this.polyline = [...polyline]
          }
          // console.log(path)
          // 在地图加载完成后，将地图的中心点设置为标记的位置
          i++
        }

        this.timer = setInterval(() => {
          renderPoint()
        }, 250)
        // requestAnimationFrame(renderPoint)
        this.$forceUpdate();
      },
      handleSearch() {
        if (!this.datetimerange.length) {
          Toast('请选择时间！')
          return
        }
        let days = daysBetween(this.datetimerange[0], this.datetimerange[1])
        if (days > 7) {
          Toast('查询时间跨度不能超过七天！')
          return
        }
        let startTime = moment(this.datetimerange[0]).valueOf()
        let endTime = moment(this.datetimerange[1]).valueOf()

        const start = getZeroTimeOfDayAlternative(startTime)
        const end = getEndOfDayTimeAlternative(endTime)
        this.getDetail(start, end)
      },
      moveMarkerToCenter(marker) {
        //将marker移动至中心点
        this.mapContext.moveToLocation({
          longitude: marker.lon,
          latitude: marker.lat,
          success: (res) => {
            //这里加300ms的延时是为了防止和moveToLocation功能冲突，保留地图移动的动画
            const timer = setTimeout(() => {
              this.longitude = marker.lon;
              this.latitude = marker.lat;
              clearTimeout(timer);
              //进行缩放，设置为16
              this.scale = 16;
            }, 300);
          },
        });
      },
      handleMarkerClick(e) {
        // 找到之后打开
        // 关闭其他的
        this.markers.forEach((item) => {
          item.customCallout = {
            anchorY: 0,
            anchorX: 0,
            display: 'BYCLICK'
          }
        })
        const id = e.detail.markerId
        const markerIndex = this.markers.findIndex((item) => {
          return item.id == id
        })
        if (~markerIndex) {
          this.markers[markerIndex].customCallout = {
            anchorY: 0,
            anchorX: 0,
            display: 'ALWAYS'
          }
          const marker = this.markers[markerIndex]

          // 再移动到中心
          this.moveMarkerToCenter({
            ...marker,
            lon: marker.longitude,
            lat: marker.latitude
          })
        }
      },
      handleAddressInfo(item) {
        this.handleMarkerClick({
          ...item,
          detail: {
            markerId: item.id
          },
          lon: item.longitude,
          lat: item.latitude
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .root {
    width: 100%;
    height: 100%;
    overflow: auto;
    position: relative;

    .customCallout {
      box-sizing: border-box;
      border-radius: 2px;
      display: flex;
      padding: 5px 20px;
      background: #fff;
      flex-direction: column;
      width: 434rpx;
      text-align: left;
    }

    .time-text {
      font-weight: 400;
      font-size: 28rpx;
      color: #AAAAAA;
    }

    .content-address {
      font-weight: 500;
      font-size: 28rpx;
      color: #000000;
      line-height: 42rpx;
      white-space: normal;
    }

    .top-item {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 434rpx;
      border-radius: 10rpx 10rpx 10rpx 10rpx;

      .name {
        font-weight: bold;
        font-size: 30rpx;
        color: #FFFFFF;
        height: 67rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #FC590E;
      }

      .address {
        font-weight: bold;
        font-size: 28rpx;
        color: #000000;
        padding: 15rpx 28rpx;
        background: #FFFFFF;
      }
    }

    .bottom {
      padding: 36rpx 25rpx 36rpx 25rpx;

      .t-box {
        display: flex;
        align-items: center;
        margin-bottom: 60rpx;

        .time-item {
          width: 147rpx;
          height: 56rpx;
          background: linear-gradient(94deg, #D2EFFE 0%, #F3FBFF 100%);
          border-radius: 28rpx 28rpx 28rpx 28rpx;
          border: 1rpx solid #B8E3F8;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #2488F5;
          font-weight: 500;
          font-size: 28rpx;
          margin-right: 22rpx;
        }

        .time-selected {
          color: #FFFFFF;
          background: linear-gradient(94deg, #51B1FF 0%, #1790F2 100%);
        }

        .time-3 {}
      }

      .btn-box {
        margin-top: 30rpx;

        /deep/ .u-button__text {
          font-weight: 500;
          font-size: 36rpx !important;
          color: #FFFFFF;
        }
      }

      .btn-style {
        max-height: 400px;
        overflow: auto;
        margin-top: 42rpx;

        .c-item {
          display: flex;
          padding-bottom: 43rpx;
          position: relative;

          &:last-child {
            .solid-style {
              display: none;
            }
          }

          .b-item {
            width: 38rpx;
            height: 38rpx;
            background: #FC590E;
            border-radius: 12rpx 12rpx 12rpx 12rpx;
            flex-shrink: 0;
            margin-right: 12rpx;
            position: relative;
            z-index: 10;
          }

          .solid-style {
            content: '';
            position: absolute;
            left: 19rpx;
            width: 1px;
            background: #dddddd;
            height: 100%;
            z-index: 1;


          }

          .b-time {
            font-weight: 500;
            font-size: 28rpx;
            color: #666666;
            margin-bottom: 12rpx;
          }

          .style-b {}

          .b-address {
            font-weight: bold;
            font-size: 28rpx;
            color: #000000;
          }
        }
      }
    }
  }
</style>